package org.msb.accentis.data;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import javax.persistence.Persistence;

public class DataManagerFactory {

	private static DataManagerFactory instance = new DataManagerFactory();
	
	private IDataManager currentDataManager;
	
	private Set<IDataManagerFactoryListener> dataManagerFactoryListeners = new HashSet<IDataManagerFactoryListener>();
	
	public static DataManagerFactory getInstance() {
		return instance;
	}
	
	public IDataManager createDataManager(String location, char[] password) {
		Map<String, String> properties = new HashMap<String, String>();
		properties.put("openjpa.ConnectionURL", "jdbc:derby:" + location
				+ "/.db;create=true;bootPassword=" + String.valueOf(password));

		return changeCurrentDataManager(new DataManager(Persistence.createEntityManagerFactory("accentis", properties)));
	}

	public IDataManager openDataManager(String location, char[] password) {
		Map<String, String> properties = new HashMap<String, String>();
		properties.put("openjpa.ConnectionURL", "jdbc:derby:" + location
				+ "/.db;bootPassword=" + String.valueOf(password));

		return changeCurrentDataManager(new DataManager(Persistence.createEntityManagerFactory("accentis", properties)));
	}
	
	private IDataManager changeCurrentDataManager(IDataManager dataManager) {
		currentDataManager = dataManager;
		
		for (IDataManagerFactoryListener listener : dataManagerFactoryListeners)
			listener.dataManagerChanged(currentDataManager);
		
		return currentDataManager;
	}
	
	public IDataManager getDataManager() {
		return currentDataManager;
	}
	
	public void addDataManagerFactoryListener(IDataManagerFactoryListener listener) {
		dataManagerFactoryListeners.add(listener);
	}
	
	public void removeDataManagerFactoryListener(IDataManagerFactoryListener listener) {
		dataManagerFactoryListeners.remove(listener);
	}
}
